package com.surelution.projects.crm
import java.text.NumberFormat
import java.text.SimpleDateFormat
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import java.util.Date;

class NoGasListController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	def exportService
	
    def index = {
        redirect(action: "report", params: params)
    }
	/**
	 * 上传非油品对应类型——自己做的
	 */
	def ngTImport = {
		def file = params.noGasTypeFile
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(file.inputStream, "GBK"))
		reader.eachLine {line->
			String[] words = line.split()
			NoGasType noGasType = new NoGasType(nonGasDescription:"${words[0]}",nonGasType:"${words[1]}")
			noGasType.save(flush:true)
		}
        flash.message = "上传成功！"
		redirect(action:"typeCreate")
    }
	
	def typeCreate = {
	}
	/**
	 * 上传所有非油品消费清单
	 */
	def ImportExcelService
	def springSecurityService
	def ngImport = {
		def file = params.noGasFile
		int lineNum = 0
		def fileName = file.originalFilename
		ImportExcel excel = ImportExcelService.storeFile(file.inputStream,fileName)
		
		def sdf = new SimpleDateFormat('yyyy.MM.dd')
		BufferedReader reader = new BufferedReader(new InputStreamReader(file.inputStream, "utf-16"))
		reader.eachLine {line->
			if(lineNum > 3) {
				String[] words = line.split()
				if(words.length > 8) {
					Date saleTime = sdf.parse(words[8])
					NoGasList noGasList = new NoGasList()
					noGasList.saleTime = saleTime
					noGasList.noGasType = words[2]
					noGasList.stationCode = words[0]
					noGasList.stationName = words[1]
					noGasList.number = words[3]
					noGasList.price = words[4]
					noGasList.income = words[5]
					noGasList.maoLi = words[6]
					noGasList.maoLiRate = words[7]
					noGasList.save()
					println noGasList
					
					float number = Float.parseFloat("${words[3].replaceAll(',','').replaceAll('"','')}")
					float price = Float.parseFloat("${words[4].replaceAll(',','').replaceAll('"','')}")
					float income = Float.parseFloat("${words[5].replaceAll(',','').replaceAll('"','')}")
					float maoLi = Float.parseFloat("${words[6].replaceAll(',','').replaceAll('"','')}")
					float cost = price*income
					NoGasSale noGasSale = new NoGasSale(number:"${number}",price:"${price}",income:"${income}",cost:"${cost}",maoLi:"${maoLi}")
					
					noGasSale.station = OwnStation.findByCode("${words[0]}")
					if (NoGasType.findByNonGasDescription("${words[2]}")){
						noGasSale.noGasType = NoGasType.findByNonGasDescription("${words[2]}")
					}
					noGasSale.saleTime = saleTime
					noGasSale.save()
					println noGasSale
					flash.message = "${message(code: 'default.updateFileSuccess.message', args: [message(code: 'noGasList.label', default: 'noGasList')])}"
				}
			}
			lineNum++
		}
		excel.uploader = springSecurityService.principal.username
		excel.type = "非油品消费明细"
		excel.save()
		redirect(action:"list")
	}
	def GasReportService
/**
 * 非油品时间段查询显示、导出、分析
 */
	def report = {
		def result
		def startDay = new Date()
		def endDay = new Date()
		def areaIds = []
		if (params.startDay&& params.endDay){
			startDay = params.startDay
			endDay = params.endDay
			def stationArea = params.stationArea
			if(stationArea instanceof String) {
				areaIds.add(Long.parseLong(stationArea))
			} else {
				stationArea.each {id->
					areaIds.add(Long.parseLong(id))
				}
			}
			result = GasReportService.noGasReport(startDay,endDay,areaIds)
			if (!result){
				flash.message = "${message(code: 'default.nofound.message')}"
				redirect(action: "report")
			}
		}
		[result:result,startDay:startDay,endDay:endDay,stationArea:areaIds]
	}
	def reportExport = {
		def result
		def startDay,endDay
		def areaIds = []
		if (params.startDay&& params.endDay){
			startDay = params.startDay
			endDay = params.endDay
			def stationArea = params.stationArea
			if(stationArea instanceof String) {
				areaIds.add(Long.parseLong(stationArea))
			} else {
				stationArea.each {id->
					areaIds.add(Long.parseLong(id))
				}
			}
			result = GasReportService.noGasReport(startDay,endDay,areaIds)
			response.contentType = ConfigurationHolder.config.grails.mime.types['excel']
			response.setHeader("Content-disposition", "attachment; filename=NoGasSale.xls")
			def mapList = new ArrayList<HashMap>()
			def typeSize = NoGasTypeCategory.list().size()
			result.each {
				def map = new HashMap()
				def i = 2
				map.put("area", it[0].areaName)
				map.put('stationName', it[1].name)
				NoGasTypeCategory.list().each {st->
					map.put(st.name.toString(), parseNumber(it[i].toString(),1))
					i++
				}
				map.put('allNums', it[typeSize+2])
				map.put('maoLi', parseNumber(it[typeSize+3].toString(),1))
				map.put('rate', parseNumber(it[typeSize+4].toString(),1))
				mapList.add(map)
			}
			List fields = ['stationName','area']
			Map labels = ['stationName':"站名", 'area':"片区"]
			NoGasTypeCategory.list().each {st->
				fields.add((st.name).toString())
				labels.put((st.name).toString(), st.name+"(元)")
			}
			fields.add("allNums")
			labels.put("allNums", "总收入(元)")
			fields.add("maoLi")
			labels.put("maoLi", "毛利(元)")
			fields.add("rate")
			labels.put("rate", "毛利率(%)")
			exportService.export("excel", response.outputStream, mapList, fields, labels,[:],[:])
		}
	}
	
	
	def planReport = {
		def result
		def startDay = new Date()
		def endDay = new Date()
		def areaIds = []
		if (params.startDay&& params.endDay){
			startDay = params.startDay
			endDay = params.endDay
			def stationArea = params.stationArea
			if(stationArea instanceof String) {
				areaIds.add(Long.parseLong(stationArea))
			} else {
				stationArea.each {id->
					areaIds.add(Long.parseLong(id))
				}
			}
			result = GasReportService.noGasPlanReport(startDay,endDay,areaIds)
			if (!result){
				flash.message = "${message(code: 'default.nofound.message')}"
				redirect(action: "planReport")
			}
		}
		[pResult:result,startDay:startDay,endDay:endDay,stationArea:areaIds]
	}

	def planReportExport = {
		def result
		def startDay,endDay
		def areaIds = []
		if (params.startDay&& params.endDay){
			startDay = params.startDay
			endDay = params.endDay
			def stationArea = params.stationArea
			if(stationArea instanceof String) {
				areaIds.add(Long.parseLong(stationArea))
			} else {
				stationArea.each {id->
					areaIds.add(Long.parseLong(id))
				}
			}
			result = GasReportService.noGasPlanReport(startDay,endDay,areaIds)
			if (!result){
				flash.message = "${message(code: 'default.nofound.message')}"
				redirect(action: "planReport")
			}
			response.contentType = ConfigurationHolder.config.grails.mime.types['excel']
			response.setHeader("Content-disposition", "attachment; filename=NoGasPlanList.xls")
			def mapList = new ArrayList<HashMap>()
			def typeSize = NoGasTypeCategory.list().size()
			result.each {
				def map = new HashMap()
				def i = 2
				map.put("area", it[0].areaName)
				map.put('stationName', it[1].name)
				map.put('planNums', it[3])
				map.put('saleNums', it[4])
				map.put('planRate', it[5])
				mapList.add(map)
			}
			List fields = ['stationName','area','planNums','saleNums','planRate']
			Map labels = [ 'area':"片区",'stationName':"站名",'planNums':"计划总量(元)",'saleNums':"总收入(元)",'planRate':"计划完成量(%)"]
			exportService.export("excel", response.outputStream, mapList, fields, labels,[:],[:])
		}
		[pResult:result,startDay:startDay,endDay:endDay,stationArea:areaIds]
	}
	
	
	/**
	* 处理float数值，最大保留3位
	* @param s
	* @param i
	* @return
	*/
   def parseNumber(String s,int i){
	   NumberFormat nf = NumberFormat.getInstance();
	   float d = Float.valueOf(s);
	   nf.setMinimumFractionDigits(i);
	   nf.setMaximumFractionDigits(i);
	   def number = nf.parse(nf.format(d)).floatValue()
	   return number
   }
	
	/**
	 * 非油品同比环比查询
	 */
	def compareReport = {
		def result,cResult
		def startDay = new Date()
		def endDay = new Date()
		def startDayA = new Date()
		def endDayA = new Date()
		def areaIds = []
		if (params.startDay&& params.endDay&&params.startDayA&& params.endDayA){
			startDay = params.startDay
			endDay = params.endDay
			startDayA = params.startDayA
			endDayA = params.endDayA
			def stationArea = params.stationArea
			if(stationArea instanceof String) {
				areaIds.add(Long.parseLong(stationArea))
			} else {
				stationArea.each {id->
					areaIds.add(Long.parseLong(id))
				}
			}
			result = compareNoGasReport(startDay,endDay,startDayA,endDayA,areaIds)
		}
		[result:result,startDay:startDay,endDay:endDay,startDayA:startDayA,endDayA:endDayA,stationArea:areaIds]
	}
	
	def compareReportExport = {
		def result,cResult
		def startDay = new Date()
		def endDay = new Date()
		def startDayA = new Date()
		def endDayA = new Date()
		def areaIds = []
		if (params.startDay&& params.endDay&&params.startDayA&& params.endDayA){
			startDay = params.startDay
			endDay = params.endDay
			startDayA = params.startDayA
			endDayA = params.endDayA
			def stationArea = params.stationArea
			if(stationArea instanceof String) {
				areaIds.add(Long.parseLong(stationArea))
			} else {
				stationArea.each {id->
					areaIds.add(Long.parseLong(id))
				}
			}
			result = compareNoGasReport(startDay,endDay,startDayA,endDayA,areaIds)
			def typeSize = NoGasTypeCategory.list().size()
			def mapList = new ArrayList<HashMap>()
			response.contentType = ConfigurationHolder.config.grails.mime.types['excel']
			response.setHeader("Content-disposition", "attachment; filename=ComNoGasPlan.xls")
			result.each{
				def map = new HashMap()
				map.put("area", it.get("area"))
				map.put("station", it.get("station"))
				(1..typeSize).each {i->
					map.put((NoGasTypeCategory.get(i).name+"A"), it.get(NoGasTypeCategory.get(i).name+"A"))
					map.put((NoGasTypeCategory.get(i).name+"B"), it.get(NoGasTypeCategory.get(i).name+"B"))
				}
				map.put("priceA", it.get("priceA"))
				map.put("priceB", it.get("priceB"))
				map.put("maoLiA", it.get("maoLiA"))
				map.put("maoLiB", it.get("maoLiB"))
				map.put("maoLiRateA", it.get("maoLiRateA"))
				map.put("maoLiRateB", it.get("maoLiRateB"))
				mapList.add(map)
			}
			List fields = ['station','area']
			Map labels = [ 'area':"片区",'station':"站名"]
			(1..typeSize).each {type->
				fields.add((NoGasTypeCategory.get(type).name+"A"))
				labels.put((NoGasTypeCategory.get(type).name+"A"), "前-"+NoGasTypeCategory.get(type).name)
				}
			fields.add("priceA")
			labels.put("priceA", "前-总收入(元)")
			fields.add("maoLiA")
			labels.put("maoLiA", "前-毛利(元)")
			fields.add("maoLiRateA")
			labels.put("maoLiRateA", "前-毛利率(%)")
			(1..typeSize).each {type->
				fields.add((NoGasTypeCategory.get(type).name+"B"))
				labels.put((NoGasTypeCategory.get(type).name+"B"), "后-"+NoGasTypeCategory.get(type).name)
				}
			fields.add("priceB")
			labels.put("priceB", "后-总收入(元)")
			fields.add("maoLiB")
			labels.put("maoLiB", "后-毛利(元)")
			fields.add("maoLiRateB")
			labels.put("maoLiRateB", "后-毛利率(%)")
			exportService.export("excel", response.outputStream, mapList, fields, labels,[:],[:])
		}
	}
	
	def compareNoGasReport(Date startDay, Date endDay,Date startDayA, Date endDayA,areaIds){
		def result,cResult
		def typeSize = NoGasTypeCategory.list().size()
		if (startDay&&endDay&&areaIds){
			result = GasReportService.noGasReport(startDay,endDay,areaIds)
		}
		println result
		if (startDayA&&endDayA&&areaIds){
			cResult = GasReportService.noGasReport(startDayA,endDayA,areaIds)
		}
		def cMap = new HashMap()
		cResult.each {
			cMap.put(it[1],it)
		}
		if (!result||!cResult){
			flash.message = "${message(code: 'default.nofound.message', args: [message(code: 'gasList.label', default: 'GasList')])}"
			redirect(action: "compareReport")
		}
		def mapList = new ArrayList<HashMap>()
		result.each{
			def map = new HashMap()
			map.put("area", it[0].areaName)
			map.put("station", it[1].shortName)
			def nullList = []
			(0..  typeSize+3).each{
				nullList.add(0)
			}
			def cr = cMap.get(it[1])?cMap.get(it[1]):nullList
			
			(1..typeSize).each {i->
				map.put((NoGasTypeCategory.get(i).name+"A"), it[i+1])
				map.put((NoGasTypeCategory.get(i).name+"B"), cr[i+1])
			}
			map.put("priceA", it[typeSize+2])
			map.put("priceB", cr[typeSize+2])
			map.put("maoLiA", it[typeSize+3])
			map.put("maoLiB", cr[typeSize+3])
			map.put("maoLiRateA", it[typeSize+4])
			map.put("maoLiRateB", cr[typeSize+4])
			mapList.add(map)
		}
		return mapList
	}
	
/**
 * 非油品同比环比计划完成量显示、导出、分析	
 */
	def comparePlanReport = {
		def result,cResult
		def startDay = new Date()
		def endDay = new Date()
		def startDayA = new Date()
		def endDayA = new Date()
		def areaIds = []
		if (params.startDay&& params.endDay&&params.startDayA&& params.endDayA&&params.stationArea){
			startDay = params.startDay
			endDay = params.endDay
			startDayA = params.startDayA
			endDayA = params.endDayA
			def stationArea = params.stationArea
			if(stationArea instanceof String) {
				areaIds.add(Long.parseLong(stationArea))
			} else {
				stationArea.each {id->
					areaIds.add(Long.parseLong(id))
				}
			}
			result = compareNoGasPlanReport(startDay,endDay,startDayA,endDayA,areaIds)
		}
		[result:result,startDay:startDay,endDay:endDay,startDayA:startDayA,endDayA:endDayA,stationArea:areaIds]
	}
	
	def comparePlanReportExport = {
		def result,cResult
		def startDay = new Date()
		def endDay = new Date()
		def startDayA = new Date()
		def endDayA = new Date()
		def areaIds = []
		if (params.startDay&& params.endDay&&params.startDayA&& params.endDayA&&params.stationArea){
			startDay = params.startDay
			endDay = params.endDay
			startDayA = params.startDayA
			endDayA = params.endDayA
			def stationArea = params.stationArea
			if(stationArea instanceof String) {
				areaIds.add(Long.parseLong(stationArea))
			} else {
				stationArea.each {id->
					areaIds.add(Long.parseLong(id))
				}
			}
			result = compareNoGasPlanReport(startDay,endDay,startDayA,endDayA,areaIds)
			def mapList = new ArrayList<HashMap>()
			response.contentType = ConfigurationHolder.config.grails.mime.types['excel']
			response.setHeader("Content-disposition", "attachment; filename=ComNoGasPlanList.xls")
			List fields = ['station','area','planNumsA','saleNumsA','planRateA','planNumsB','saleNumsB','planRateB']
			Map labels = [ 'area':"片区",'station':"站名",'planNumsA':"前-计划量(元)",'saleNumsA':"前-总收入(元)",'planRateA':"前-计划完成量(%)",'planNumsB':"后-计划量(元)",'saleNumsB':"后-总收入(元)",'planRateB':"后-计划完成量(%)"]
			exportService.export("excel", response.outputStream, result, fields, labels,[:],[:])
		}
	}
	
	def compareNoGasPlanReport(Date startDay, Date endDay,Date startDayA, Date endDayA,areaIds){
		def result,cResult
		result = GasReportService.noGasPlanReport(startDay,endDay,areaIds)
		cResult = GasReportService.noGasPlanReport(startDayA,endDayA,areaIds)
		if (!result||!cResult){
			flash.message = "${message(code: 'default.nofound.message', args: [message(code: 'gasList.label', default: 'GasList')])}"
			redirect(action: "comparePlanReport")
		}
		def cMap = new HashMap()
		cResult.each {
			cMap.put(it[1],it)
		}
		def mapList = new ArrayList<HashMap>()
		result.each{
			def map = new HashMap()
			if (cMap.get(it[1])){
				def c = cMap.get(it[1])
				map.put("planNumsB", parseNumber(c[2].toString(),1))
				map.put("saleNumsB", parseNumber(c[3].toString(),1))
				map.put("planRateB", parseNumber((c[5]).toString(),2))
			}
			else{
				map.put("planNumsB", 0)
				map.put("saleNumsB", 0)
				map.put("planRateB", 0)
			}
			map.put("area", it[0].areaName)
			map.put("station", it[1].shortName)
			map.put("stationName", it[1].name)
			map.put("planNumsA", parseNumber(it[2].toString(),1))
			map.put("saleNumsA", parseNumber(it[3].toString(),1))
			map.put("planRateA", parseNumber((it[5]).toString(),2))
			
			mapList.add(map)
		}
		return mapList
	}
	
    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
		def sdf = new SimpleDateFormat('yyyy-MM-dd')
		def dateFrom = params.dateFrom? sdf.parse(params.dateFrom):null
		def dateTo = params.dateTo? sdf.parse(params.dateTo):null
		def stationCode = params['station.id']?OwnStation.get(params['station.id']).code.toString():null
		def result = NoGasList.createCriteria().list ([max:params.max, offset:params.offset]){
			if(stationCode){
				eq("stationCode",stationCode)
			}
			if(dateFrom) {
				ge("saleTime", dateFrom)
			}
			if(dateTo) {
				le("saleTime", dateTo)
			}
		}
        [noGasListInstanceList: result, noGasListInstanceTotal: result.totalCount]
    }

    def create = {
        def noGasListInstance = new NoGasList()
        noGasListInstance.properties = params
        return [noGasListInstance: noGasListInstance]
    }

    def save = {
        def noGasListInstance = new NoGasList(params)
        if (noGasListInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'noGasList.label', default: 'NoGasList'), noGasListInstance.id])}"
            redirect(action: "show", id: noGasListInstance.id)
        }
        else {
            render(view: "create", model: [noGasListInstance: noGasListInstance])
        }
    }

    def show = {
        def noGasListInstance = NoGasList.get(params.id)
        if (!noGasListInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'noGasList.label', default: 'NoGasList'), params.id])}"
            redirect(action: "list")
        }
        else {
            [noGasListInstance: noGasListInstance]
        }
    }

    def edit = {
        def noGasListInstance = NoGasList.get(params.id)
        if (!noGasListInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'noGasList.label', default: 'NoGasList'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [noGasListInstance: noGasListInstance]
        }
    }

    def update = {
        def noGasListInstance = NoGasList.get(params.id)
        if (noGasListInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (noGasListInstance.version > version) {
                    
                    noGasListInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'noGasList.label', default: 'NoGasList')] as Object[], "Another user has updated this NoGasList while you were editing")
                    render(view: "edit", model: [noGasListInstance: noGasListInstance])
                    return
                }
            }
            noGasListInstance.properties = params
            if (!noGasListInstance.hasErrors() && noGasListInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'noGasList.label', default: 'NoGasList'), noGasListInstance.id])}"
                redirect(action: "show", id: noGasListInstance.id)
            }
            else {
                render(view: "edit", model: [noGasListInstance: noGasListInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'noGasList.label', default: 'NoGasList'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def noGasListInstance = NoGasList.get(params.id)
        if (noGasListInstance) {
            try {
                noGasListInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'noGasList.label', default: 'NoGasList'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'noGasList.label', default: 'NoGasList'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'noGasList.label', default: 'NoGasList'), params.id])}"
            redirect(action: "list")
        }
    }
}
